package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbvtc.agriculturalcreditchainserver2025.dto.CouponDto.DeskillCouponDto;
import com.tbvtc.agriculturalcreditchainserver2025.dto.CouponDto.OrdinaryCouponDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Coupon;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUserHolder;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICouponService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/voucher")
@Tag(name = "优惠券")
public class
VoucherController {
    @Resource
    private ICouponService couponService;

    @PostMapping("/addOrdinaryCoupons")
    @Operation(summary = "新增普通优惠券")
    public Result addCoupon(@RequestBody OrdinaryCouponDto ordinaryCouponDto) {
        Coupon coupon = BeanUtil.copyProperties(ordinaryCouponDto, Coupon.class);
        coupon.setCouponType(0);
        Snowflake snowflake = new Snowflake(1L, 1L); // workerId, datacenterId
        long id = snowflake.nextId();
        coupon.setId(String.valueOf(id));
        coupon.setFarmerId(LoginUserHolder.getLoginUser().getUserId());
        couponService.save(coupon);
        return RUtils.success(coupon.getId());

    }

    @PostMapping("/addDeskillCoupons")
    @Operation(summary = "新增秒杀优惠券")
    public Result addDeskillCoupons(@RequestBody DeskillCouponDto deskillCouponDto) {
        return RUtils.success(couponService.addDeskillCoupons(deskillCouponDto));
    }

    @GetMapping
    @Operation(summary = "查询用户的优惠券")
    @Parameters({@Parameter(name = "farmerId", description = "用户id"),
            @Parameter(name = "couponType", description = "优惠券类型")})
    public Result getCouponsByFarmerId(Integer farmerId, Integer couponType) {
        List<Coupon> list = couponService.list(new LambdaQueryWrapper<Coupon>()
                .eq(couponType != null, Coupon::getCouponType, couponType)
                .eq(Coupon::getFarmerId, farmerId)
        );

        return RUtils.success(list);
    }

    @Operation(summary = "根据优惠卷id查询优惠券详情")
    @GetMapping("/getCouponInfo")
    public Result getCouponInfo(String couponId) {
        Coupon coupon = couponService.getById(couponId);
        return RUtils.success(coupon);
    }


}
